package com.tangula.web.config.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 跨域处理拦截器.
 * @author 王东石 &lt;wangds2016@163.com&gt;
 *
 */
@Service
public class CorsInterceptor implements HandlerInterceptor {
	private static final String METHOD_NAME_GET = RequestMethod.GET.name();
	private static final String METHOD_NAME_OPTION = RequestMethod.OPTIONS.name();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String req_method = request.getMethod();
		if(StringUtils.equalsAnyIgnoreCase(req_method, METHOD_NAME_OPTION, METHOD_NAME_GET)) {
			response.addHeader("Access-Control-Allow-Origin", "*");
			response.addHeader("Access-Control-Max-Age", "3628800");
			response.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS");
			response.addHeader("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
		}
		
		return !StringUtils.equalsIgnoreCase(req_method, METHOD_NAME_OPTION);
	}
}
